package com.javatest.chapter3;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2020-04-13 22:59
 */
public class AsyncFutureExample2 {
    /**
     * 定义线程池
     */
    private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
    private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingDeque<>(5), new ThreadPoolExecutor.CallerRunsPolicy());

    public static String doingSomethingA() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("----doing something A----");
        return "Task A Result";
    }

    public static String doingSomethingB() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("----doing something B----");
        return "Task B Result";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        // 1.开启异步执行单元A
        final Future<String> futureBTask = POOL_EXECUTOR.submit(() -> {
            String result = null;
            try {
                result = doingSomethingA();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        });

        // 2.执行任务B
        String taskResult = doingSomethingB();

        // 3.同步等待线程A运行结束
        String taskAResult = futureBTask.get();

        // 4.打印两个任务运行结果
        System.out.println("task a result " + taskAResult);
        System.out.println(System.currentTimeMillis() - start);

        POOL_EXECUTOR.shutdown();
    }
}
